package com.yingli.network;

import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

//import org.apache.http.client.HttpClient;

public class HttpClientActivity extends AppCompatActivity {

    private TextView tvWeb;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpclient);
       requestData();
//        HttpClient
    }

    private void requestData() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                HttpClient client = new DefaultHttpClient();
                tvWeb = findViewById(R.id.tv_web);
                HttpGet httpGet = new HttpGet("http://www.12306.cn/mormhweb/");
                try {
                    HttpResponse response = client.execute(httpGet);
                    if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                        HttpEntity entity = response.getEntity();
                        InputStream inputStream = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuilder builder = new StringBuilder();
                        while (true) {
                            String temp;
                            if ((temp = reader.readLine()) != null) {
                                builder.append(temp);
                            }else {
                                break;
                            }
                        }
                        runOnUiThread(()->{
                            tvWeb.setText(builder.toString());
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
